# encoding=utf8
from WordSimilarity import main as WS
from WordSimilarity import utils
import main as ner
from flask import  Flask,request
import jieba
import json

app = Flask(__name__)

# 提取关键词接口
@app.route('/extract_key_word', methods=["GET"])
def ExtractKeyWord():
    sentence = request.args.get('sentence')
    res = ner.server(sentence)
    print(res)
    return res

# 词语相似度接口
@app.route('/word_similarity', methods=["GET"])
def WordSimilarity():
    word1 = request.args.get('word1')
    word2 = request.args.get('word2')
    score = WS.HybridSim.get_Final_sim(word1,word2)
    print(word1,word2)
    return str(score)

'''
    标准答案关键词字符串
    学生答案字符串
    比较相似度
'''
@app.route('/keylist_answer_similarity', methods=["GET"])
def AnswerSimilarity():
    key_str = request.args.get('key')
    ans_str = request.args.get('ans')
    answer = ner.server(ans_str)
    # answer = ner.server('仓储是指利用仓库进行物品的入库、存贮、出库的活动。')
    strans = ''
    for each in answer['entities']:
        strans = strans+','+each['word']
    strlist = utils.move_stopwords(utils.seg_depart(key_str)) # 分词
    anslist = utils.move_stopwords(utils.seg_depart(strans))
    print('关键词列表：',strlist)
    print('答案列表：',anslist)
    simlist = WS.GetMaxList(strlist,anslist)
    score = WS.GetStrSim(strlist,anslist)
    # print('相似度列表：',simlist)
    # print('相似度得分：',str(score))
    simlist.insert(0,score)
    print(simlist)
    return json.dumps(simlist)

# 短句相似度接口
# @app.route('/sentence_similarity', methods=["GET"])
def SentenceSimilarity(sentence1,sentence2):
    # sentence1 = request.args.get('sentence1')
    # sentence2 = request.args.get('sentence2')
    sentence1_list = utils.move_stopwords(utils.seg_depart(sentence1))  # 分词
    sentence2_list = utils.move_stopwords(utils.seg_depart(sentence2))
    # print('切分后：',sentence1_list,sentence2_list)
    len1 = len(sentence1_list)
    len2 = len(sentence2_list)
    score = 0
    for sen1 in sentence1_list:
        if sen1 in sentence2_list: # 如果该词已在第二句子列表中
            score += 1
            sentence2_list.remove(sen1)  # 在第二个句子中删除该词
            continue
        maxsim = 0
        for sen2 in sentence2_list:
            sim = WS.HybridSim.get_Final_sim(sen1, sen2)
            if sim > maxsim:
                maxsim = sim
        score += maxsim
    # print(score)
    return score/([len1,len2][len1<len2])# 取长度较大值，如果取长度较小值可能出现得分大于1，考虑取1

'''
    标准答案关键词字符串，通过中文逗号分割
    学生答案字符串
    比较词语相似度
    得出每个得分点得分[得分点，匹配项，相似度]
'''
@app.route('/keylist_answer_similarity_point', methods=["GET"])
def AnswerSimilarityPoint():
    key_str = request.args.get('key')
    ans_str = request.args.get('ans')
    # key_str = '仓储管理，内容:仓库，选址，建设，仓库机械设备，配置，仓库业务管理，仓库，库存控制管理，人力资源管理'
    # ans_str = '仓库的选址与建设'
    ans_ner = ner.server(ans_str)
    key_list = key_str.split('，')
    ans_list = []
    for each in ans_ner['entities']:
        ans_list.append(each['word'])
    print('key_list:',key_list)
    print('ans_list:',ans_list)
    result = []
    for point in key_list:
        max_score = 0.0
        match_ans = ''
        if point in ans_list:
            result.append([point,point,1.0])
            ans_list.remove(point)
            # print(point,'存在')
            continue
        for ans in ans_list:
            score = SentenceSimilarity(point,ans)
            # print(point,'与',ans,'匹配度：',score)
            if score > max_score:
                max_score = score
                match_ans = ans
                if max_score == 1.0:
                    ans_list.remove(ans)
                    break
        if max_score > 0.3:
            result.append([point, match_ans, max_score])
        else:
            result.append([point, '', 0])
    # 计算得分
    num = len(key_list)
    point = 0
    for each in result:
        point += each[2]
    result.insert(0, point/num)
    print(result)
    return json.dumps(result)

'''
    标准答案得分点字符串，通过中文逗号分割
    学生答案字符串
    通过调用孪生网络
    得出每个得分点得分[得分点，匹配项，相似度]
'''
@app.route('/keylist_answer_similarity_siamese', methods=["GET"])
def AnswerSimilarityPointSiamese():
    key_str = request.args.get('key')
    ans_str = request.args.get('ans')
    # key_str = '仓储管理，内容:仓库，选址，建设，仓库机械设备，配置，仓库业务管理，仓库，库存控制管理，人力资源管理'
    # ans_str = '仓库的选址与建设'
    ans_ner = ner.server(ans_str)
    key_list = key_str.split('，')
    ans_list = []
    for each in ans_ner['entities']:
        ans_list.append(each['word'])
    print('key_list:',key_list)
    print('ans_list:',ans_list)
    result = []
    for point in key_list:
        max_score = 0.0
        match_ans = ''
        if point in ans_list:
            result.append([point,point,1.0])
            ans_list.remove(point)
            # print(point,'存在')
            continue
        for ans in ans_list:
            score = SentenceSimilarity(point,ans) # 在此处调用孪生网络
            # print(point,'与',ans,'匹配度：',score)
            if score > max_score:
                max_score = score
                match_ans = ans
                if max_score == 1.0:
                    ans_list.remove(ans)
                    break
        if max_score > 0.3:
            result.append([point, match_ans, max_score])
        else:
            result.append([point, '', 0])
    # 计算得分
    num = len(key_list)
    point = 0
    for each in result:
        point += each[2]
    result.insert(0, point/num)
    print(result)
    return json.dumps(result)

'''
    标准答案字符串
    学生答案字符串
    得出每个得分点得分[得分点，匹配项，相似度]
'''
@app.route('/key_answer_similarity', methods=["GET"])
def KeyAnswerSimilarity():
    key_str = request.args.get('key')
    ans_str = request.args.get('ans')
    # key_str = '配送模式：自营配送模式、共同配送模式、第三方配送。'
    # ans_str = '补货方式包括：拼/整箱补货、托盘补货、货位补货、其它补货方式'
    key_ner,ans_ner = ner.evaluate_line_2(key_str,ans_str)
    key_list = []
    for each in key_ner['entities']:
        key_list.append(each['word'])

    ans_list = []
    for each in ans_ner['entities']:
        ans_list.append(each['word'])
    print('key_list:',key_list)
    print('ans_list:',ans_list)
    result = []
    for point in key_list:
        max_score = 0.0
        match_ans = ''
        if point in ans_list:
            result.append([point,point,1.0])
            ans_list.remove(point)
            # print(point,'存在')
            continue
        for ans in ans_list:
            score = SentenceSimilarity(point,ans)
            # print(point,'与',ans,'匹配度：',score)
            if score > max_score:
                max_score = score
                match_ans = ans
                if max_score == 1.0:
                    ans_list.remove(ans)
                    break
        if max_score > 0.3:
            result.append([point, match_ans, max_score])
        else:
            result.append([point, '', 0])
    # 计算得分
    num = len(key_list)
    point = 0
    for each in result:
        point += each[2]
    result.insert(0, point/num)
    print(result)
    return json.dumps(result)

'''
    标准答案字符串
    学生答案字符串
    通过调用孪生网络
    得出每个得分点得分[得分点，匹配项，相似度]
'''
@app.route('/key_answer_similarity_siamese', methods=["GET"])
def KeyAnswerSimilaritySiamese():
    key_str = request.args.get('key')
    ans_str = request.args.get('ans')
    # key_str = '配送模式：自营配送模式、共同配送模式、第三方配送。'
    # ans_str = '补货方式包括：拼/整箱补货、托盘补货、货位补货、其它补货方式'
    key_ner,ans_ner = ner.evaluate_line_2(key_str,ans_str)
    key_list = []
    for each in key_ner['entities']:
        key_list.append(each['word'])

    ans_list = []
    for each in ans_ner['entities']:
        ans_list.append(each['word'])
    print('key_list:',key_list)
    print('ans_list:',ans_list)
    result = []
    for point in key_list:
        max_score = 0.0
        match_ans = ''
        if point in ans_list:
            result.append([point,point,1.0])
            ans_list.remove(point)
            # print(point,'存在')
            continue
        for ans in ans_list:
            score = SentenceSimilarity(point,ans) #在此处调用孪生网络
            # print(point,'与',ans,'匹配度：',score)
            if score > max_score:
                max_score = score
                match_ans = ans
                if max_score == 1.0:
                    ans_list.remove(ans)
                    break
        if max_score > 0.3:
            result.append([point, match_ans, max_score])
        else:
            result.append([point, '', 0])
    # 计算得分
    num = len(key_list)
    point = 0
    for each in result:
        point += each[2]
    result.insert(0, point/num)
    print(result)
    return json.dumps(result)

if __name__ == '__main__':
    # print(ner.server('汽车运输调度员的职业功能及对应的工作内容主要包括：A.市场调查与预测分析。货主需求调查；货运车辆情况调查。B.编制运行计划。收集路况、车辆、货源信息；编排货物运输计划。C.实施运行计划。调整车辆；处理意外事件；组织货物运输。D.监督检查。查验证件；安全监督。E.信息资料管理。运输单证管理；整理数据。'))
    # AnswerSimilarityPoint()
    # print(SentenceSimilarity('仓储设施布局','仓储作业计划'))
    # StringToStringSimilarity()
    app.run(port=8089,debug=True)
    # KeyAnswerSimilarity()
